package com.thwj.project.monitor.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thwj.common.utils.StringUtils;
import com.thwj.common.utils.WzDateUtil;
import com.thwj.framework.security.LoginUser;
import com.thwj.project.app.api.param.ActivityParam;
import com.thwj.project.app.service.AppActivityService;
import com.thwj.project.biz.domain.Activity;
import com.thwj.project.biz.enums.ActivityStatusEnum;
import com.thwj.project.biz.service.IActivityService;
import com.thwj.project.biz.service.IActivitySignupService;
import com.thwj.project.push.MpPushMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Slf4j
@Transactional
@Service("JobTask")
public class JobTask {

    @Autowired
    AppActivityService appActivityService;
    @Autowired
    IActivityService activityService;
    @Autowired
    IActivitySignupService activitySignupService;
    @Autowired
    MpPushMessageService mpPushMessageService;

    /***
     * 更新报名中的活动
     * 30秒 一次
     */
    public void activityStatusUpdate() {
        // 只要没有没结束的 活动都需要扫一遍更新状态
        List<Activity> activityList = activityService.list(
                new QueryWrapper<Activity>()
                        .lt("status", ActivityStatusEnum.end.getValue())
        );
        activityList.forEach(item->{
            appActivityService.updateActivityStatusAuto(item);
        });
        log.info("定时任务更新活动状态，当前时间更新条数 {}", activityList.size());
    }

    /***
     * 报名费用结算至组织者账户
     * 活动结束 次日 0点1分触发 2023-06-15 13:00:00活动结束 那么就是23年6月16号0点1分结算至账户
     * 每天0点1分触发一次
     */
    public void activitySignUpSettle2Account() {
        activitySignUpSettle2Account(null);
    }

    public void activitySignUpSettle2Account(String endDate) {
        Date activityEndDay = null;
        if(StringUtils.isEmpty(endDate)) {
            activityEndDay = WzDateUtil.setDate(WzDateUtil.getBeginOfTheDay(new Date()),-2);
        }else {
            activityEndDay = WzDateUtil.string2Date(endDate,WzDateUtil.DATE_FORMAT);
        }

        // 只要没有没结束的 活动都需要扫一遍更新状态
        List<Activity> activityList = activityService.list(
                new QueryWrapper<Activity>()
                        .eq("status", ActivityStatusEnum.end.getValue())
                        .between("end_date", WzDateUtil.getBeginOfTheDay(activityEndDay),WzDateUtil.getEndOfTheDay(activityEndDay))
        );
        // 读取出 报名需要费用的活动id
        activityList.forEach(activity -> {
            // 开启事务 每个活动在一个事务里处理
            try {
                appActivityService.activitySignUpSettle2Account(activity.getId());
            } catch (Exception e) {
                log.error("定时任务处理活动费用结算异常, activity:{}, e :{}",activity,e);
            }
        });

        log.info("定时任务更新活动状态，当前时间更新条数 {}", activityList.size());
    }

    /***
     * 提醒管理员发起订单
     *
     */
    public void pushAdminOrderPay() {
        String activityParamJson = "{\"address\":\"浙江省杭州市滨江区缤纷路600号\",\"cancelFreeType\":1,\"categoryId\":6,\"chargeType\":1,\"coverPic\":\"\",\"describeContent\":\"测试支付专用\",\"describePic\":\"\",\"discountType\":0,\"discountedPrice\":0,\"endDate\":1700662920000,\"formType\":1,\"latitude\":30.2084,\"longitude\":120.21201,\"maxManCount\":0,\"maxSignUpCount\":2,\"maxWomanCount\":0,\"name\":\"杭州市滨江区人民政府(新月路北)\",\"payWay\":1,\"picList\":\"https://daya-dev.oss-cn-hangzhou.aliyuncs.com/app/user/16909858152180.18454786021448544.jpeg\",\"price\":1.32,\"showPublic\":false,\"startDate\":1700662560000,\"title\":\"测试支付专用\",\"type\":1}";

        int randomPrice = new Random().nextInt(10);
        activityParamJson = activityParamJson.replace("1.32",String.valueOf(randomPrice * 1.0 / 10));

        ActivityParam activityParam = JSON.parseObject(activityParamJson,ActivityParam.class);
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(2L);
        // 创建一个固定的 活动
        Activity activity = appActivityService.createUpdateActivity(activityParam, loginUser);

//        mpPushMessageService.pushMessageWxMpAdminMessageEvent(WxMpAdminMessageEvent.builder()
//                .pushTemplateEnum(PushTemplateEnum.MERCHANT_ACTIVITY_CREATE_SUCCESS)
//                .miniAppPath("pages/detail/detail?activityId=" + activity.getId())
//                .templateDataList(PushTemplateEnum.getMERCHANT_ACTIVITY_CREATE_SUCCESS_Data(
//                        "【90天内连续30天支付专用】",
//                        activity.getTitle(),
//                        activity.getStartDate() ,
//                        // 活动名称 以及 组局人的联系方式
//                        activity.getContactPhone()))
//                .build()
//        );

    }
}
